package com.duan.nowcoder.community.controller;

import com.duan.nowcoder.community.entity.User;
import com.duan.nowcoder.community.service.UserService;
import com.duan.nowcoder.community.util.*;
import com.google.code.kaptcha.Producer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

@Controller
public class LoginController implements CommunityConstant {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private Producer kaptchaProducer;
    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private RedisUtil redisUtil;


    //访问主页
    @GetMapping("/register")
    public String getRegisterPage() {
        return "/site/register";
    }

    //访问登录界面
    @GetMapping("/login")
    public String getLoginPage() {
        return "/site/login";
    }

    //注册请求
    @PostMapping("/register")
    public String register(Model model, User user) {
        Map<String, Object> map = userService.register(user);
        if (map == null || map.isEmpty()) {
            model.addAttribute("msg", "注册成功，我们已将您的验证信息发送至您的邮箱，请尽快验证！");
            model.addAttribute("url", "/index");
            return "/site/operate-result";
        } else {
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            model.addAttribute("emailMsg", map.get("emailMsg"));
        }
        return "/site/register";
    }

    //激活账号并跳转
    @GetMapping("/activation/{userId}/{code}")
    public String activation(Model model, @PathVariable("userId") int userId, @PathVariable("code") String code) {
        int activation = userService.activation(userId, code);
        if (activation == ACTIVATION_SUCCESS) {
            model.addAttribute("msg", "您已激活成功，将自动为您跳转至登录页面");
            model.addAttribute("url", "/login");
        } else if (activation == ACTIVATION_REPEAT) {
            model.addAttribute("msg", "您的账号已激活，请勿重复激活，将自动为您跳转至登录页面");
            model.addAttribute("url", "/login");
        } else {
            model.addAttribute("msg", "您的激活码无效，激活失败！");
            model.addAttribute("url", "/index");
        }
        return "/site/operate-result";
    }

    @GetMapping("/kaptcha")
    public void getKaptcha(HttpServletResponse response/*, HttpSession session*/) {
        //生成验证码
        String text = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(text);

        /*//将验证码存入session
        session.setAttribute("kaptcha", text);*/
        //将验证码存入redis
        String kaptcha = CommunityUtil.generateUUID();
        String kaptchaKey = RedisKeyUtil.getKaptchaKey(kaptcha);
        redisUtil.set(kaptchaKey, text, 60);
        //将验证码存入Cookie
        Cookie cookie = new Cookie("kaptchaOwner", kaptchaKey);
        cookie.setMaxAge(60);
        cookie.setPath(contextPath);
        response.addCookie(cookie);
        //将图片传给浏览器
        response.setContentType("image/png");
        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "PNG", os);
        } catch (IOException e) {
            logger.error("图片输出错误" + e.getMessage());
        }
    }

    @PostMapping("/login")
    public String login(String username, String password,
                        String code, Model model,
                        boolean rememberMe, HttpServletResponse respones,
                        @CookieValue("kaptchaOwner") String kaptchaOwner) {
        //验证码为空
        if (code == null || StringUtils.isBlank(code)) {
            model.addAttribute("codeMsg", "请填写验证码!");
            return "/site/login";
        }
        //验证码错误
        //String kaptcha = (String) session.getAttribute("kaptcha");
        //获得验证码
        String kaptcha = null;
        if (StringUtils.isNoneBlank(kaptchaOwner))
            kaptcha = (String) redisUtil.get(kaptchaOwner);
        if (StringUtils.isBlank(kaptcha) || !kaptcha.equalsIgnoreCase(code)) {
            model.addAttribute("codeMsg", "验证码填写错误！");
            return "/site/login";
        }
        //检查账号密码
        int expiredSecond = rememberMe ? EXPIRED_SECOND_REMEMBER : EXPIRED_SECOND_DEFAULT;
        Map<String, Object> map = userService.login(username, password, expiredSecond);
        if (map.containsKey("ticket")) {
            Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
            //获得该cookie的范围
            cookie.setPath(contextPath);
            cookie.setMaxAge(expiredSecond);
            respones.addCookie(cookie);
            return "redirect:/index";
        } else {
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            return "/site/login";
        }
    }

    @GetMapping("/logout")
    public String logout(@CookieValue("ticket") String ticket) {
        userService.logout(ticket);
        hostHolder.clear();
        SecurityContextHolder.clearContext();
        return "/site/login";
    }

    @GetMapping("/enied")
    public String enied(){
        return "/error/500";
    }

}
